﻿package com.android.losscheck;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ref.SoftReference;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.Matrix;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class CommUtil {
	
	/** 最大图片限制 */
//	public static final int IMAGE_MAX_BYTE = 1024 * 1024;
	public static final int IMAGE_MAX_BYTE = 1024 *1024;

	public static boolean checkNetState(Context context){
    	boolean netstate = false;
		ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if(connectivity != null)
		{
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++)
				{
					if (info[i].getState() == NetworkInfo.State.CONNECTED)
					{
						netstate = true;
						break;
					}
				}
			}
		}
		return netstate;
    }
	
	public static void showToask(Context context, String tip){
		Toast.makeText(context, tip, Toast.LENGTH_SHORT).show();
	}

    /**
     * 将图片截取为圆角图片
     * @param bitmap 原图片
     * @param ratio 截取比例，如果是8，则圆角半径是宽高的1/8，如果是2，则是圆形图片
     * @return 圆角矩形图片
     */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float ratio) {
	        
	        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
	                        bitmap.getHeight(), Config.ARGB_8888);
	        Canvas canvas = new Canvas(output);

	        final Paint paint = new Paint();
	        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
	        final RectF rectF = new RectF(rect);

	        paint.setAntiAlias(true);
	        canvas.drawARGB(0, 0, 0, 0);
	        canvas.drawRoundRect(rectF, bitmap.getWidth()/ratio, 
	                        bitmap.getHeight()/ratio, paint);

	        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
	        canvas.drawBitmap(bitmap, rect, rect, paint);
	        return output;
	}
	
	
	/**
	 * 放大缩小图片
	 * 
	 * @param bitmap
	 * @param w
	 * @param h
	 * @return
	 */
	public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
		Bitmap newbmp = null;
		if (bitmap != null) {
			int width = bitmap.getWidth();
			int height = bitmap.getHeight();
			Matrix matrix = new Matrix();
			float scaleWidht = ((float) w / width);
			float scaleHeight = ((float) h / height);
			matrix.postScale(scaleWidht, scaleHeight);
			newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
					true);
		}
		return newbmp;
	}
	
	
    /**
     * 将图片截取为圆形
     * @param bitmap 原图片
     * @param ratio 截取比例，如果是8，则圆角半径是高的1/8，如果是2，则是圆形
     * @return 圆形图片
     */
    public static Bitmap getRoundedBitmap(Bitmap bitmap, float ratio) {
            
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                            bitmap.getHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(output);

            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            final RectF rectF = new RectF(rect);

            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            canvas.drawRoundRect(rectF, bitmap.getHeight()/ratio, 
                            bitmap.getHeight()/ratio, paint);

            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);
            return output;
    }
    

    public static String getVersionName(Context context){
    	try {
    		PackageManager packageManager = context.getPackageManager();
    		PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(),0);
    		if(packInfo!=null){
    			return packInfo.versionName;
    		}
    	}catch (Exception e) {
    		// TODO: handle exception
    		e.printStackTrace();
    	}
    	return null;  
    }
    
	//文件存放路径，优先sdcard
    public static String getFileName(Context context,String name){
        boolean isSdcardEnable = false;
        String state = Environment.getExternalStorageState();
        if(Environment.MEDIA_MOUNTED.equals(state)){//SDCard�Ƿ����
            isSdcardEnable = true;
        }
        String dbPath = null;
        if(isSdcardEnable){
            dbPath = Environment.getExternalStorageDirectory().getPath() + "/sanxing/";
        }else{
            dbPath = context.getFilesDir().getPath() + "/sanxing/";
        }
        File dbp = new File(dbPath);
        if(!dbp.exists()){
            dbp.mkdirs();
        }
        return dbPath+name;
    }
    
	//获取图片文件
	public static File getPicFile(Context context,String picName){
		File file = null;
		
			file = new File(getFileName(context,picName));
			if(!file.exists()){
				try {
					file.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		return file;
	}


//文件存放路径，优先sdcard
public static String getMyDatabaseName(Context context,String name){
    boolean isSdcardEnable = false;
    String state = Environment.getExternalStorageState();
    if(Environment.MEDIA_MOUNTED.equals(state)){//SDCard�Ƿ����
        isSdcardEnable = true;
    }
    String dbPath = null;
    if(isSdcardEnable){
        dbPath = Environment.getExternalStorageDirectory().getPath() + "/sanxing/";
    }else{
        dbPath = context.getFilesDir().getPath() + "/sanxing/";
    }
    File dbp = new File(dbPath);
    if(!dbp.exists()){
        dbp.mkdirs();
    }
    return dbPath+name;
}

/**
 * 写图片文件到SD卡
 * 
 * @throws IOException
 */
public static void saveImageToSD(Context ctx, String filePath,
		Bitmap bitmap, int quality) throws IOException {
	if (bitmap != null) {
		File file = new File(filePath.substring(0,
				filePath.lastIndexOf(File.separator)));
		if (!file.exists()) {
			file.mkdirs();
		}
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(filePath));
		bitmap.compress(CompressFormat.JPEG, quality, bos);
		bos.flush();
		bos.close();
//		if(ctx!=null){
//			scanPhoto(ctx, filePath);
//		}
	}
}

/**
 * 转换为小于512KB的图片
 * @param image
 * @return
 */
	public static Bitmap getSmallBitmap(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int options = 100;
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		// 512KB
		while (baos.toByteArray().length > IMAGE_MAX_BYTE) { 
			baos.reset();
			options -= 10;
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
		return bitmap;
	}
	
	/**
	 * 图片按比例大小压缩方法（根据Bitmap图片压缩）：
	 * @param image
	 * @return
	 */
	public static Bitmap comp(Bitmap image) {
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();		
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出	
			baos.reset();//重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		//开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		//现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;//这里设置高度为800f
		float ww = 480f;//这里设置宽度为480f
		//缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;//be=1表示不缩放
		if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;//设置缩放比例
		//重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
	}
	
	/**
	 * 图片按比例大小压缩方法（根据路径获取图片并压缩）
	 * @param srcPath
	 * @return
	 */
	public static Bitmap getimage(String srcPath) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		//开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空
		
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		//现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;//这里设置高度为800f
		float ww = 480f;//这里设置宽度为480f
		//缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;//be=1表示不缩放
		if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;//设置缩放比例
		//重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
	}
	
	private static Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while ( baos.toByteArray().length / 1024>100) {	//循环判断如果压缩后图片是否大于100kb,大于继续压缩		
			baos.reset();//重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;//每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
		return bitmap;
	}
	
//	/** 从给定的路径加载图片，并指定是否自动旋转方向*/  
//    public static Bitmap loadBitmap(String imgpath, boolean adjustOritation) {  
//        if (!adjustOritation) {  
//            return loadBitmap(imgpath);  
//        } else {  
//            Bitmap bm = loadBitmap(imgpath);  
//            int digree = 0;  
//            ExifInterface exif = null;  
//            try {  
//                exif = new ExifInterface(imgpath);  
//            } catch (IOException e) {  
//                e.printStackTrace();  
//                exif = null;  
//            }  
//            if (exif != null) {  
//                // 读取图片中相机方向信息  
//                int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,  
//                        ExifInterface.ORIENTATION_UNDEFINED);  
//                // 计算旋转角度  
//                switch (ori) {  
//                case ExifInterface.ORIENTATION_ROTATE_90:  
//                    digree = 90;  
//                    break;  
//                case ExifInterface.ORIENTATION_ROTATE_180:  
//                    digree = 180;  
//                    break;  
//                case ExifInterface.ORIENTATION_ROTATE_270:  
//                    digree = 270;  
//                    break;  
//                default:  
//                    digree = 0;  
//                    break;  
//                }  
//            }  
//            if (digree != 0) {  
//                // 旋转图片  
//                Matrix m = new Matrix();  
//                m.postRotate(digree);  
//                bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),  
//                        bm.getHeight(), m, true);  
//            }  
//            return bm;  
//        }  
//    }  
	
	public static Bitmap decodeByteArray(byte[] data) {
		// decode image size
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeByteArray(data, 0, data.length, o);
		
		// decode with inSampleSize
		BitmapFactory.Options o2 = new BitmapFactory.Options();
		int scale = data.length/IMAGE_MAX_BYTE;
		if (scale < 1) {
			scale = 1;
		}
		o2.inSampleSize = scale;
		ByteArrayInputStream input = new ByteArrayInputStream(data);
	    SoftReference softRef = new SoftReference(BitmapFactory.decodeStream(input, null, o2));
	    Bitmap  bitmap = (Bitmap)softRef.get();

		return bitmap;
	}
	
	/**  
     * 对象转数组  
     * @param obj  
     * @return  
     */  
    public static byte[] toByteArray (Object obj) {      
        byte[] bytes = null;      
        ByteArrayOutputStream bos = new ByteArrayOutputStream();      
        try {        
            ObjectOutputStream oos = new ObjectOutputStream(bos);         
            oos.writeObject(obj);        
            oos.flush();         
            bytes = bos.toByteArray ();      
            oos.close();         
            bos.close();        
        } catch (IOException ex) {        
            ex.printStackTrace();   
        }      
        return bytes;    
    }   
       
    /**  
     * 数组转对象  
     * @param bytes  
     * @return  
     */  
    public static Object toObject (byte[] bytes) {      
        Object obj = null;      
        try {        
            ByteArrayInputStream bis = new ByteArrayInputStream (bytes);        
            ObjectInputStream ois = new ObjectInputStream (bis);        
            obj = ois.readObject();      
            ois.close();   
            bis.close();   
        } catch (IOException ex) {        
            ex.printStackTrace();   
        } catch (ClassNotFoundException ex) {        
            ex.printStackTrace();   
        }      
        return obj;    
    }   
}
